"""
@Project:p8_syl_flask
@File:comment.py
@Author:郑凯乐
@Date:16:13
"""
import json
from common.models import db
from flask import Blueprint,jsonify,g
from flask_restful import Api,Resource,reqparse,marshal
from common.models.course import Course,Comments
from common.models.user import UserModels
from common.model_fields.course import comment_fields
from common.model_fields.user_fields import user_fields
from common.utils.login_utils import login_required

comment_bp = Blueprint('comment', __name__, url_prefix='/comment')

api = Api(comment_bp)

class CommentsResource(Resource):
    # 获取评论
    def get(self):
        try:
            parser = reqparse.RequestParser()
            parser.add_argument('course_id')
            args = parser.parse_args()
            course_id = args.get('course_id')
            if course_id:
                comment = Comments.query.filter_by(course = course_id).all()
                comments = marshal(comment, comment_fields)
                # 把有序字典转成字典
                result = json.loads(json.dumps(comments))
                # 循环
                for i in result:
                    user = UserModels.query.filter_by(uid=i["user"]).first()
                    users = marshal(user,user_fields)
                    i["user_info"] = users
                    parent_comment = Comments.query.filter_by(parent_id = i["id"]).all()
                    parent_comment = marshal(parent_comment,comment_fields)
                    parent_comment = json.loads(json.dumps(parent_comment))
                    for j in parent_comment:
                        user = UserModels.query.filter_by(uid = j["user"]).first()
                        user = marshal(user,user_fields)
                        j["user_info"] = user
                    i["childlist"] = parent_comment
                return jsonify(message="ok！", code=200, data=result)
        except Exception as e:
            print(e)
            return jsonify(message="服务器错误！", code=500)

    #发表，回复评论
    @login_required
    def post(self):
        try:
            parse = reqparse.RequestParser()
            parse = parse.add_argument("content")
            parse = parse.add_argument("cid")
            parse = parse.add_argument("reply")
            args = parse.parse_args()
            content = args.get("content")
            cid = args.get("cid")
            parent_id = args.get("reply")
            print("发表评论", content, cid, parent_id)
            user_id = g.user_id
            if not user_id:
                return jsonify(message="请重新登录！", code=401)
            if cid != None:
                comment = Comments(user=user_id, course=cid, comment_content=content)
            else:
                comment = Comments(user=user_id, course=parent_id, comment_content=content)

                comment_one = Comments.query.filter_by(id=parent_id).first()
                if not comment_one:
                    return jsonify(message="该评论不存在！", code=401)

                # 更新回复量
                Comments.query.filter_by(id=parent_id).update({"reply_count": comment_one.reply_count + 1})
                db.session.commit()

            db.session.add(comment)
            db.session.commit()
            return jsonify(message="发表成功！", code=200, )
        except Exception as e:
            print(e)
            return jsonify(message="服务器错误！", code=500)


class CommentlikeResource(Resource):
    def post(self):
        try:
            parse = reqparse.RequestParser()
            parse = parse.add_argument("com_id")
            parse = parse.add_argument("is_favorite")
            args = parse.parse_args()
            com_id = args.get('com_id')
            is_favorite = args.get("is_favorite")
            print("数据", com_id, is_favorite, type(is_favorite))
            comment = Comments.query.filter_by(id=com_id).first()
            if not comment:
                return jsonify(message="该评论不存在",code=401)
            up_comment = Comments.query.filter_by(id=com_id)
            # 更新点赞量
            if is_favorite == "True":
                up_comment.update({"zan_num": comment.zan_num + 1})
            else:
                up_comment.update({"zan_num": comment.zan_num - 1})
            db.session.commit()
            return jsonify(message="ok！", code=200, )

        except Exception as e:
            print(e)
            return jsonify(message="服务器错误！", code=500)

api.add_resource(CommentsResource, '/get_comment')
api.add_resource(CommentlikeResource, "/favorite_comment")
